/*
 * @Author: Jimmy
 * @LastModifiedBy: Jimmy
 * @Date: 2024-05-12 11:26:07
 * @LastEditTime: 2024-08-23 22:58:34
 * @FilePath: /nest_study/server/src/common/filters/http-exceptions-filter.ts
 */
import { Catch, HttpException, ExceptionFilter, ArgumentsHost, Logger } from '@nestjs/common';

@Catch(HttpException)
export class HttpExceptionsFilter implements ExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    const start = Date.now();
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest<Request>();  //  这里可以得到请求的绝大部分信息
    const reqHeaders: any = request.headers  //得到请求头信息
    const status = exception.getStatus();
    const exceptionResponse = exception.getResponse();
    const urlInfo = `${request.method} ${request.url}`;
    Logger.error(`请求接口: ${urlInfo}, 响应时间: ${Date.now() - start} ms 响应消息：${exception.message} 请求来源: ${reqHeaders.host}`)
    response.status(200).json({
      code: status,
      msg: exceptionResponse?.message ? exception.message : 'Service Error',
      data: null,
    });
  }
}
